package com.zf.spring.microservice.zuul.webapi;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.config.ConfigurationManager;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.filters.FilterRegistry;
import com.zf.spring.microservice.zuul.common.filters.FilterInfo;

/**
 * 提供REST API <br/>
 * 查询 <br/>
 * 禁用/启用<br/>
 * 
 * @author zhangfeng
 * 
 */
@RestController
@RequestMapping("zuul-api")
public class FilterController {
	/** 罗列所有filter */
	@RequestMapping("/filters")
	public ArrayList<FilterInfo> listFilters() throws Exception {
		ArrayList<FilterInfo> res = new ArrayList<FilterInfo>();
		// 反射获取信息
		Field field = FilterRegistry.instance().getClass()
				.getDeclaredField("filters");
		field.setAccessible(true);
		ConcurrentHashMap<String, ZuulFilter> filters = (ConcurrentHashMap<String, ZuulFilter>) field
				.get(FilterRegistry.instance());
		Set<Entry<String, ZuulFilter>> entrySet = filters.entrySet();
		for (Entry<String, ZuulFilter> entry : entrySet) {
			res.add(FilterInfo.convertZuulFilter(entry.getKey(),
					entry.getValue()));
		}
		return res;
	}

	/** 根据type查询filter */
	@RequestMapping("/filters/type/{type}")
	public ArrayList<FilterInfo> listFiltersByType(
			@PathVariable("type") String type) throws Exception {
		ArrayList<FilterInfo> res = new ArrayList<FilterInfo>();
		Field field = FilterRegistry.instance().getClass()
				.getDeclaredField("filters");
		field.setAccessible(true);
		ConcurrentHashMap<String, ZuulFilter> filters = (ConcurrentHashMap<String, ZuulFilter>) field
				.get(FilterRegistry.instance());
		Set<Entry<String, ZuulFilter>> entrySet = filters.entrySet();
		for (Entry<String, ZuulFilter> entry : entrySet) {
			if (entry.getValue().filterType().equals(type)) {
				res.add(FilterInfo.convertZuulFilter(entry.getKey(),
						entry.getValue()));
			}
		}
		return res;
	}

	/** 根据key查询filter */
	@RequestMapping("/filters/key/{key}")
	public FilterInfo listFiltersByKey(@PathVariable("key") String key) {
		return FilterInfo.convertZuulFilter(key,
				FilterRegistry.instance().get(key));
	}
	
	/** 启用/禁用filter */
	@RequestMapping("/filters/on-off/{key}")
	public FilterInfo turnOn_OffByKey(@PathVariable("key") String key) {
		FilterInfo convertZuulFilter = FilterInfo.convertZuulFilter(key,FilterRegistry.instance().get(key));
		ConfigurationManager.getConfigInstance().setProperty(convertZuulFilter.getDisablePropertyName(), !convertZuulFilter.isFilterDisabled());
		return convertZuulFilter;
	}
}
